import { ref } from "vue";
import { modifyEmail } from '@/api/user.api';
import { omit, pick } from 'lodash-es';
import { useI18n } from 'vue-i18n';
import { sendCode } from '@/api/user.api';
import useUserStore from '@/store/modules/user';

export function useFormState() {
  const userStore = useUserStore();
  const { t } = useI18n();
  const formRef = ref();
  const formState = ref({
    email: '',
    code: '',
    password: '',
    sendType: 'register', 
    type: 1
  });
  const rules = {
    email: [
      {
        required: true,
        errorMessage: t('register.form.email.validate.required'),
      },
      {
        format: 'email',
        errorMessage: t('register.form.email.validate.required'),
      }
    ],
    code: [
      {
        required: true,
        errorMessage: t('register.form.captcha.validate.required'),
      }
    ],
    password: [
      {
        required: true,
        errorMessage: t('register.form.password.validate.required'),
      }
    ],
  }



  const handleSubmit = () => {

    formRef.value.validate().then(res => {
      modifyEmail(omit(formState.value, ['sendType', 'type'])).then(({ data }) => {
        


      if(data.status === 200) {

        uni.hideLoading();
        userStore.getUserInfo().then(() => {
          uni.navigateBack()
        })
      }else {
        
      }


      })
    }).catch(errors => {
      uni.showToast({
        title: '倒计时结束后再发送'
      });
    })
  }

  return {
    formRef,
    formState,
    rules,
    handleSubmit
  }

}



export function useAuthCode(formState) {
  const { t } = useI18n();
  const countdown = ref(0)
  const codeHint = ref('获取验证码');


  function startCountdown() {
    countdown.value = 60;
    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value -= 1;

        codeHint.value = `${countdown.value}秒后重新发送`;
      } else {
        clearInterval(timer);
        codeHint.value = '获取验证码';
      }
    }, 1000);
  }

  function handleSendCode() {
    if (countdown.value > 0) {
      return
    }
    startCountdown()
    sendCode(pick(formState.value, ['email', 'sendType', 'type']))
  }

  return {
    countdown,
    codeHint,
    handleSendCode
  }
}